package com.lagou.edu.user.controller;

import com.lagou.edu.common.UserManager;
import com.lagou.edu.common.regex.RegexUtil;
import com.lagou.edu.common.result.ResponseDTO;
import com.lagou.edu.user.api.UserRemoteService;
import com.lagou.edu.user.api.dto.UserDTO;
import com.lagou.edu.user.service.UserService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @author lm
 * @since 2021/10/15 15:54
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口", produces = "application/json")
@Slf4j
public class UserController {
    @Autowired
    UserRemoteService userRemoteService;

    @Autowired
    UserService userService;

    @ApiOperation(value = "用户登录", produces = MimeTypeUtils.APPLICATION_JSON_VALUE, notes = "用户登录, 未注册用户会自动注册并登录")
    @ApiResponses({
            @ApiResponse(code = 201, message = "非法的手机号"),
            @ApiResponse(code = 202, message = "密码或者验证码为空"),
            @ApiResponse(code = 203, message = "验证码错误"),
            @ApiResponse(code = 204, message = "验证码过期"),
            @ApiResponse(code = 205, message = "手机号或者密码错误"),
            @ApiResponse(code = 206, message = "登录失败"),
            @ApiResponse(code = 207, message = "验证码错误"),
            @ApiResponse(code = -1, message = "login fail"),
            @ApiResponse(code = 1, message = "success")
    })
    @PostMapping("login")
    public ResponseDTO<String> login(@ApiParam(name = "phone", value = "手机号", required = true) String phone,
                                     @ApiParam(name = "password", value = "密码") String password,
                                     @ApiParam(name = "code", value = "验证码") String code) {
        if (StringUtils.isEmpty(phone) || !RegexUtil.isPhone(phone)) {
            return ResponseDTO.ofError(201, "非法的手机号");
        }
        if (StringUtils.isEmpty(password) && StringUtils.isEmpty(code)) {
            return ResponseDTO.ofError(202, "密码或者验证码为空");
        }
        // 默认是账号密码登录
        Integer type = 0;
        if (StringUtils.isEmpty(password) && !StringUtils.isEmpty(code)) {
            type = 1;
        }

        // 判断手机号是否有注册
        boolean isRegister = userRemoteService.isRegister(phone);
        if (!Boolean.TRUE.equals(isRegister)) {
            // 不允许直接手机号+密码注册并登录
            if (type == 0) {
                log.info("该手机号[{}]未注册,不允许手机号+密码注册", phone);
                return ResponseDTO.ofError(205, "手机号或者密码错误");
            }
            UserDTO dto = new UserDTO();
            dto.setAccountNonExpired(true);
            dto.setAccountNonLocked(true);
            dto.setCredentialsNonExpired(true);
            dto.setStatus("ENABLE");
            dto.setRegIp(UserManager.getUserIP());
            dto.setName(phone);
            dto.setPassword(type == 0 ? password : phone);
            dto.setCreateTime(new Date());
            dto.setIsDel(false);
            dto.setPhone(phone);
            dto.setUpdateTime(new Date());
            dto.setPortrait(null);
            UserDTO newUser = this.userRemoteService.saveUser(dto);
            log.info("用户[{}]注册成功", newUser);
        }
        return userService.createAuthToken(phone, password, code, type);
    }

    @ApiOperation("查询所有用户信息")
    @GetMapping("/getAllUsers")
    public ResponseDTO<List<UserDTO>> getAllUsers() {
        return ResponseDTO.success(userRemoteService.getAllUsers());
    }

    @ApiOperation("保存用戶")
    @PostMapping("/saveUser")
    public ResponseDTO<UserDTO> saveUser(@RequestBody UserDTO userDTO) {
        return ResponseDTO.success(userRemoteService.saveUser(userDTO));
    }

    @ApiOperation("更新用戶")
    @PostMapping("/updateUser")
    public ResponseDTO<Boolean> updateUser(@RequestBody UserDTO userDTO) {
        return ResponseDTO.success(userRemoteService.updateUser(userDTO));
    }

    @ApiOperation("更新用戶密碼")
    @PostMapping("/updatePassword")
    public ResponseDTO<Boolean> updatePassword(@RequestParam("userId") Integer userId, @RequestParam("oldPassword") String oldPassword,
                           @RequestParam("newPassword") String newPassword, @RequestParam("configPassword") String configPassword) {
        return ResponseDTO.success(userRemoteService.updatePassword(userId, oldPassword, newPassword, configPassword));
    }
}
